package com.carbon.util;

import com.carbon.common.domain.SysUser;
import com.carbon.exception.CarbonException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


/**
 * 安全服务工具类
 * 
 * @author ljxl
 */
public class SecurityUtils
{
    private static SysUser user;
    /**
     * 获取用户账户
     **/
    public static SysUser getUser()
    {
        return user;
    }

    /**
     * 判断用户是否登录
     **/
    public static boolean isLogin(String userName,String password)
    {
        boolean flag=false;
        String sql="select user_id,user_name,user_type,password from  sys_user where user_name=?";
        try(Connection conn= DBUtil.getConnection()){
            PreparedStatement pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,userName);
            ResultSet rs=pstmt.executeQuery();
            if (rs.next()){
               SysUser s=new SysUser();
                s.setUserId(rs.getLong("user_id"));
                s.setUserName(rs.getString("user_name"));
                s.setUserType(rs.getString("user_type"));
                s.setPassword(rs.getString("password"));
                if(matchesPassword(password,s.getPassword())){
                    user=s;
                    flag=true;
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            throw  new CarbonException(e.getMessage());
        }
        return flag;
    }


    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 是否为管理员
     * 
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId)
    {
        return userId != null && 1L == userId;
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        boolean flag=isLogin("admin","admin123");
        System.out.println(getUser());

    }
}
